
# import numpy as np
# import matplotlib.pyplot as plt
import ctypes
import os
import sys
import math
import urllib.request
import json
import time
import datetime
import csv


daily_price = {}
daily_price["motherboard"]     = 0
daily_price["cpu"]             = 0
daily_price["motherboard_cpu"] = 1849
daily_price["computer_case"]   = 269
daily_price["power"]           = 299
daily_price["cpu_cooler"]      = 279
daily_price["graphics_card"]   = 999
daily_price["ssd"]             = 569
daily_price["hdd"]             = 369
daily_price["memory_bank"]     = 519


csv_file = "computer.csv"
# csv_file = ".computer.csv"

csv_header = ['主板', 'CPU', '主板+CPU', '机箱', '电源', '散热器', '显卡', '固态硬盘', '机械硬盘', '内存', '风扇']
csv_number = ['100007256670', '100006445340', ]


class computer(object):
    """docstring for computer"""
    def __init__(self, date, motherboard, cpu, motherboard_cpu, computer_case, power, cpu_cooler, graphics_card, ssd, hdd, memory_bank):
        # super(computer, self).__init__()
        self.date = date
        print(self.date)
        self.motherboard = motherboard
        self.cpu = cpu

        if motherboard_cpu == 0:
            self.motherboard_cpu = motherboard + cpu
        else:
            self.motherboard_cpu = motherboard_cpu

        self.computer_case = computer_case
        self.power = power
        self.cpu_cooler = cpu_cooler
        self.graphics_card = graphics_card
        self.ssd = ssd
        self.hdd = hdd
        self.memory_bank = memory_bank

    def total_price(self):
        return (self.motherboard_cpu + self.computer_case + self.power + self.cpu_cooler + self.graphics_card + self.ssd + self.hdd + self.memory_bank)

    def list(self):
        return [self.date, self.motherboard, self.cpu, self.motherboard_cpu, self.computer_case, self.power, self.cpu_cooler, self.graphics_card, self.ssd, self.hdd, self.memory_bank]


def GenDir():
    # directory
    if os.path.exists('./AudioLog/') == False:
        os.mkdir('./AudioLog/')

    os.chdir('./AudioLog/')

    timestr = time.strftime('%Y%m%dT%H%M%S',time.localtime(time.time()))

    os.mkdir(timestr)
    os.chdir(timestr)
    print('Generate directory' + timestr)


def diagram(fileIN, fileOUT):

    # data file
    f = open('../../' + fileIN ,'rb')
    # f.seek(8,0)

    # for Mircosoft WAV file
    f.seek(48, 0)

    pcm_ori = []

    while True:
        byte = f.read(1)
        if byte == '':
            break
        else:
            hexstr =  "%s" % byte.encode('hex')
            decnum_l = int(hexstr, 16)

        byte = f.read(1)
        if byte == '':
            break
        else:
            hexstr =  "%s" % byte.encode('hex')
            decnum_h = int(hexstr, 16)

        decnum = decnum_h << 8 | decnum_l
        decnum = ctypes.c_int16(decnum).value

        # print byte, hexstr, decnum
        pcm_ori.append(decnum)

    f.close()

    # for Mircosoft WAV file
    pcm_ori = pcm_ori[:(len(pcm_ori) - 64)]

    print('pcm_ori length %d' % len(pcm_ori))


    # diagram configuration
    plt.figure(num=1, figsize=(60,40))

    plt.title('Audio', size=12)
    plt.xlabel('Sample Index', size=12)
    plt.ylabel('PCM data', size=12)


    # PCM original data
    plt.plot(pcm_ori, color='y', linestyle='--', marker='o', label='original')

    # 
    pcm_filter1 = flt1.filter(pcm_ori, 256)
    plt.plot(pcm_filter1, color='r', linestyle='--', marker='o', label='filter1')

    # 
    slope1 = flt1.slope(pcm_filter1, 100)
    plt.plot(slope1, color='g', linestyle='--', marker='o', label='slope1')

    # 
    slope_filter1 = flt1.filter(slope1, 1024)
    plt.plot(slope_filter1, color='b', linestyle='--', marker='o', label='slope_filter1')

    # 
    dct_sig = flt1.detect_sig(pcm_filter1, slope_filter1, 5000)
    plt.plot(dct_sig, color='k', linestyle='--', marker='o', label='dct_sig')

    # 
    plt.legend(loc='upper left')

    plt.savefig(fileOUT, format='png')
    # plt.show()

    print('Generate file:' + fileOUT)


def jd_price(sku):
# def jd_price(url):
    # sku = url.split('/')[-1].strip(".html")
    # print "number:" + sku
    price_url = "https://p.3.cn/prices/mgets?skuIds=J_" + sku
    response = urllib.request.urlopen(price_url)
    content = response.read()
    # print(content)
    # print(type(content))
    # print "content:" + content
    result = json.loads(str(content, encoding="utf-8"))
    # print result
    # print result[0]
    record = result[0]
    # print "price:", record['p']
    # print type(record['p'])
    return record['p']


def write_csv(path, data_row):
    with open(path,'a+',encoding='utf-8-sig') as csvfd:
        csv_writer = csv.writer(csvfd)
        csv_writer.writerow(data_row)

def main():

    print(datetime.date.today())

    new = computer(datetime.date.today(), daily_price["motherboard"], daily_price["cpu"], daily_price["motherboard_cpu"], \
                    daily_price["computer_case"], daily_price["power"], daily_price["cpu_cooler"], daily_price["graphics_card"], \
                    daily_price["ssd"], daily_price["hdd"], daily_price["memory_bank"])

    print(new.list())

    # 1. check if csv exist, if not then create one
    if os.path.exists(csv_file) == False:
        print(csv_file, "not exist")
        with open(csv_file, encoding='utf-8') as csvfd:
            csv_writer = csv.writer(csvfd)
            csv_writer.writerow(csv_header)
    else:
        print(csv_file, "exist")

    # 2. insert new data, if repetitive text, then append it
    with open(csv_file, encoding='utf-8') as csvfd:
        csv_writer = csv.writer(csvfd)
        csv_writer.writerow(new.list())

        csv_reader = csv.reader(csvfd)

        # the first is title
        header = next(csv_reader)
        print(header)
        
        for row in csv_reader:
            print(row)


    # csv_write = csv.writer(csvfd)
    # csv_write.writerow([datetime.date.today(), \
    #                 daily_price["motherboard"], daily_price["cpu"], \
    #                 daily_price["motherboard_cpu"], daily_price["computer_case"], \
    #                 daily_price["power"], daily_price["cpu_cooler"], \
    #                 daily_price["graphics_card"], daily_price["ssd"], \
    #                 daily_price["hdd"], daily_price["memory_bank"]])

    

    csvfd.close()

    # daily = computer(datetime.datetime.now(), 0, 0, 1849, )

    # sample_list = []
    # count = SAMPLE_RATE / FREQUENCY;

    # for i in range(0, count):
    #     sample_list.append(math.sin(2*math.pi*i/count) * AMPLIFY)

    # sample_int = []
    # for i in sample_list:
    #     sample_int.append(int(i))

    # print sample_int

    # i = 5
    # cycle = []
    # while i > 0:
    #     cycle.extend(sample_list)
    #     i -= 1;

    # # diagram configuration
    # plt.figure(num=1, figsize=(60,40))

    # plt.title('Sin Cycle', size=12)
    # plt.xlabel('index', size=12)
    # plt.ylabel('sin', size=12)

    # plt.plot(cycle, color='b', linestyle='--', marker='o', label='cycle')
    # plt.show()


if __name__ == '__main__':
    main()

